package com.cuit.qx.utils;



import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;


/**
 * 文件工具类
 * @author Administrator
 *
 */
public class FileUtils {

	private static final Logger logger = Logger.getLogger(String.valueOf(FileUtils.class));

	/**
	 * 检查是否有相同的文件名
	 * 
	 * @param filePath+name
	 * @return boolean
	 */
	public static boolean checkFile(String pathfileName){
		File file = new File(pathfileName);
		if(file.exists()){
			return true;
		}
		return false;
	}
	
	/**
	 * 查询文件是否存在，并且创建不存在的文件夹
	 * @param file_path
	 * @param file_name
	 * @return
	 */
	public static boolean checkFileAndCreateFile(String file_path,String file_name){
		if(checkFile(file_path + "/" + file_name)) return false;
		File file = new File(file_path);
		if(!file.exists()){
			file.mkdirs();
		}
		return true;
	}

	/**
	 * 删除文件
	 * 
	 * @param filePath+name
	 * @return boolean
	 */
	public static void deleteFile(String pathfileName) throws Exception{
		File file = new File(pathfileName);
		if(file.exists()){
			file.delete();
		}else{
			throw new Exception("要删除的文件不存在！" + pathfileName);
		}
	}

	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 * 
	 * @param delpath
	 */
	public static boolean deleteFiles(String delpath){
		File pathFile = new File(delpath);
		if (!pathFile.isDirectory()) {
			System.out.println( delpath +"不是文件夹!");
		} else if (pathFile.isDirectory()) {
			File [] files = pathFile.listFiles();
			for (File file : files) {
				if(!file.isDirectory()){
					file.delete();
				}
			}
		}
		return true;
	}
	
	/**
	 * 删除文件下过期的文件
	 * @param delpath
	 * @param time_type 时间类型：“HH” 小时、“DD” 天
 	 * @param time_num 时间数据
	 * @return
	 */
	public static boolean deleteFilesByTime(String delpath,String time_type,int time_num){
		File pathFile = new File(delpath);
		if (!pathFile.isDirectory()) {
			System.out.println( delpath +"不是文件夹!");
		} else if (pathFile.isDirectory()) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			if("HH".equals(time_type)){
				calendar.add(Calendar.HOUR, time_num);
			}else{
				calendar.add(Calendar.DATE, time_num);
			}
			long time_long = calendar.getTimeInMillis();
			File [] files = pathFile.listFiles();
			for (File file : files) {
				if(!file.isDirectory() && file.lastModified() < time_long){
					file.delete();
				}
			}
		}
		return true;
	}

	/**
	 * 得到文件的大小
	 * @return
	 */
	public static long getFileSize(String fileName [],String path){
		File file;
		long file_size = 0;
		for(String name : fileName){
			name = name.replace("/", "\\");
			if(path == null){
				file = new File(name);
				if(!file.exists()){
					logger.info("文件不存在！" + name);
					continue;
				}
			}else{
				file = new File(path + "/" + name);
				if(!file.exists()){
					logger.info("文件不存在！" + name);
					continue;
				}
			}
			file_size += file.length();
		}
		return file_size;
	}

	/**
	 * 得到问价夹下的所有文件
	 * @param pathfileName
	 * @return
	 * @throws Exception
	 */
	public static List<String> getImageNames(String pathfileName) throws Exception{
		File file = new File(pathfileName);
		List<String> list = new ArrayList<String>();
		if(file.exists()){
			File files [] = file.listFiles();
			for (File file1 : files) {
				list.add(file1.getName());
			}
		}else{
			throw new Exception("文件夹不存在！" + pathfileName);
		}
		return list;
	}

	/**
	 * 
	 * 拷贝文件
	 * @throws IOException 
	 */
	public static void copyFileUsingFileChannels(FileInputStream source, FileOutputStream local) throws IOException{    
		FileChannel inputChannel = null;
		FileChannel outputChannel = null;
		try {
			inputChannel = source.getChannel();
			outputChannel = local.getChannel();
			outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
		} finally {
			inputChannel.close();
			outputChannel.close();
		}
	}
	/**
	 * 
	 * 拷贝文件
	 */
	public static void copyFileUsingFileStreams(InputStream input, OutputStream output)
	        throws IOException {    
	    try {
	           byte[] buf = new byte[1024];        
	           int bytesRead;        
	           while ((bytesRead = input.read(buf)) > 0) {
	               output.write(buf, 0, bytesRead);
	           }
	    } finally {
	        input.close();
	        output.close();
	    }
	}
	
	/**
	 * 将String写入共享文件(覆盖模式)
	 * 
	 * @param content
	 *            写入内容
	 * @param file
	 *            目标文件
	 * @param charset
	 *            字符集
	 * @return SmbFile
	 */
	public static File writeString(String content, File file, String charset) {
		if (null != file) {
			if (null == charset || "".equals(charset)) {
				charset = "UTF-8";
			}
			PrintWriter writer = null;
			try {
				writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(file, false), charset)));
				writer.print(content);
				writer.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (writer != null) {
					try {
						writer.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return file;
	}

}
